package com.grudesign.stutrip.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.grudesign.stutrip.common.ConstantProUtils;
import com.grudesign.stutrip.service.imgService;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class imgServiceImpl implements imgService {
    @Override
    public String upLoadImg(MultipartFile file) {
        String endpoint = ConstantProUtils.END_POINT;
        String accessKeyId = ConstantProUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantProUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantProUtils.BUCKET_NAME;

        try {// 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
            filename=substring+filename;
            Date date = new Date();
            SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd");
            String dataPath = f.format(date);
            filename= "wx/"+dataPath+"/"+filename;
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            String url ="https://"+bucketName+"."+endpoint+"/"+filename;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
